﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.Web;
using SCMS.Model;
using SCMS.CoreBusinessLogic;
using SCMS.CoreBusinessLogic._GoodsReceivedNote;
using SCMS.UI.Models;
using SCMS.CoreBusinessLogic.Security;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.TenderAnalysis;
using SCMS.CoreBusinessLogic.PurchaseOrder;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.UI.GeneralHelper;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.WB;
using System.Drawing;
using SCMS.CoreBusinessLogic.Settings;
using System.IO;
using SCMS.CoreBusinessLogic._Inventory;
using System.Text;
using SCMS.CoreBusinessLogic.NotificationsManager;
using SCMS.CoreBusinessLogic.StaffServices;
using SCMS.Resource;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class GoodsReceivedNoteController : PortalBaseController
    {
        private IGoodsReceivedNoteService gRNService;
        private ITAnalysisService taService;
        private IPurchaseOrderService POService;
        private IOrderRequest ORService;
        private IWayBillService wbService;
        private InventoryService invetService;
        private INotificationService notificationService;
        private readonly IImageService m_ImageService;
        private readonly IStaffService staffService;

        public GoodsReceivedNoteController(IPermissionService permissionService, IUserContext userContext, IGoodsReceivedNoteService _goodsReceivedNoteService,
            ITAnalysisService taService, IPurchaseOrderService POService, IOrderRequest ORService, IWayBillService wrnService,
            IImageService m_ImageService, InventoryService invetService, INotificationService notificationService, IStaffService staffService)
            : base(userContext, permissionService)
        {
            this.gRNService = _goodsReceivedNoteService;
            this.taService = taService;
            this.POService = POService;
            this.ORService = ORService;
            this.wbService = wrnService;
            this.invetService = invetService;
            this.notificationService = notificationService;
            this.m_ImageService = m_ImageService;
            this.staffService = staffService;
        }

        //
        // GET: Index
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadGRN()
        {
            //Create PDF from a single URL
            //var pdfUrl = SCMS.Reports.PdfGenerator.HtmlToPdf(pdfOutputLocation: "~/Log/",
            //    outputFilenamePrefix: "GeneratedPDF",
            //    urls: new string[] { "http://localhost:56819/GoodsReceivedNote/Index/LoadGRN/" });

            ////Create PDF from multiple URLs
            //var pdfUrl = PdfGenerator.HtmlToPdf(pdfOutputLocation: "~/PDFs/",
            //    outputFilenamePrefix: "GeneratedPDF",
            //    urls: new string[] { "http://www.google.co.uk", "http://news.bbc.co.uk" });

            return LGRN("LoadGRN");
        }

        private ActionResult LGRN(string viewname)
        {
            GRNote model = new GRNote();
            model.EntityGRN = new GoodsReceivedNote();
            model.staffs = new SelectList(taService.GetStaffs(countryProg.Id), "StaffID", "StaffName");
            model.ReceivedBy = currentStaff.Id;
            //model.Suppliers = new SelectList(taService.GetSuppliers(countryProg.Id), "Id", "Name");
            model.PurchaseOrders = new SelectList(gRNService.GetGRNPurchaseOrders(countryProg.Id), "Id", "RefNumber");
            model.SubOffices = new SelectList(gRNService.GetCountrySubOffices(countryProg.Id), "Id", "Name");
            model.Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name");
            model.ApproversList = new SelectList(staffService.GetStaffByApprovalDoc(NotificationHelper.grnCode, countryProg.Id), "Id", "StaffName");
            model.EntityGRN.RefNumber = string.Format("--{0}--", Resources.GoodsReceivedNote_LoadGRN_NewGRN);
            model.POItemz = new List<POItemsView>();
            return View(viewname, model);
        }

        public ActionResult LoadGRNItemDetais(Guid PoId, string viewName)
        {
            GRNote model = new GRNote();
            model.EntityGRN = new GoodsReceivedNote();
            model.EntityGRN.PurchaseOrderId = PoId;
            model.ReceivedBy = currentStaff.Id;
            model.EntityGRN.Supplier = gRNService.GetPO(PoId).Supplier;
            model.EntityGRN.SupplierId = gRNService.GetPO(PoId).Supplier.Id;
            model.staffs = new SelectList(taService.GetStaffs(countryProg.Id), "StaffID", "StaffName");
            model.PurchaseOrders = new SelectList(gRNService.GetGRNPurchaseOrders(countryProg.Id), "Id", "RefNumber");
            model.SubOffices = new SelectList(gRNService.GetCountrySubOffices(countryProg.Id), "Id", "Name");
            model.Warehouses = new SelectList(gRNService.GetSubOfficeWareHouses(Guid.Empty), "Id", "Name");
            model.ApproversList = new SelectList(staffService.GetStaffByApprovalDoc(NotificationHelper.grnCode, countryProg.Id), "Id", "StaffName");
            model.EntityGRN.RefNumber = string.Format("--{0}--", Resources.GoodsReceivedNote_LoadGRN_NewGRN);
            model.POItemz = gRNService.GetPOItemsDetails(PoId);
            ViewBag.SupplierName = gRNService.GetPO(PoId).Supplier.Name;
            //return View("LoadGRN", model);
            return View(viewName, model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveGRN(Models.GRNote entity)
        {
            entity.EntityGRN.Id = Guid.NewGuid();
            entity.EntityGRN.CountryProgrammeId = countryProg.Id;
            entity.EntityGRN.PreparedBy = currentStaff.Id;
            entity.EntityGRN.Verified = false;
            entity.EntityGRN.PreparedOn = DateTime.Now;
            if (!gRNService.SaveGRN(entity.POItemz, entity.EntityGRN))
            {
                ViewBag.Response = 0;
                ViewBag.msg = Resources.Global_String_AnErrorOccurred;
                entity.staffs = new SelectList(taService.GetStaffs(countryProg.Id), "StaffID", "StaffName");
                entity.EntityGRN.SupplierId = gRNService.GetPO(entity.EntityGRN.PurchaseOrderId).Supplier.Id;
                entity.PurchaseOrders = new SelectList(gRNService.GetGRNPurchaseOrders(countryProg.Id), "Id", "RefNumber");
                entity.SubOffices = new SelectList(gRNService.GetCountrySubOffices(countryProg.Id), "Id", "Name");
                entity.POItemz = gRNService.GetPOItemsDetails(entity.EntityGRN.PurchaseOrderId);
                ViewBag.SupplierName = gRNService.GetPO(entity.EntityGRN.PurchaseOrderId).Supplier.Name;
                return View("LoadGRN", entity);
            }
            GoodsReceivedNote grn = gRNService.GetGRNById(entity.EntityGRN.Id);
            grn.IsSubmitted = true;
            grn.RefNumber = gRNService.GenerateUniquNumber(countryProg);
            gRNService.UpdateGRN(grn);
            //Send notification
            notificationService.SendToAppropriateApprover(NotificationHelper.grnCode, NotificationHelper.verificationCode, grn.Id);
            ViewBag.Response = 1;
            ViewBag.msg = Resources.Global_String_ProcessCompleted;
            return ShowGRNs();
        }

        public ActionResult ViewGRNs()
        {
            return ShowGRNs();
        }

        private ActionResult ShowGRNs()
        {
            List<ViewGRN> modelList = new List<ViewGRN>();
            foreach (Model.GoodsReceivedNote item in gRNService.GetGRNs(countryProg.Id))
            {
                var model = new ViewGRN()
                {
                    EntityGRN = item
                };
                modelList.Add(model);
            }
            return View("ViewGRNs", modelList);
        }

        public ActionResult DeleteGRN(Guid id)
        {
            gRNService.DeleteGRNById(id);
            return ViewGRNs();
        }

        public ActionResult VerifyGRN(Guid id)
        {
            using (var db = new SCMSEntities())
            {
                Model.GoodsReceivedNote grn = db.GoodsReceivedNotes.FirstOrDefault(p => p.Id == id);
                Model.Supplier s = grn.Supplier;
                Model.CountrySubOffice c = grn.CountrySubOffice;
                Model.Location l = c.Location;

                foreach (GoodsReceivedNoteItem grnitem in grn.GoodsReceivedNoteItems)
                {
                    Model.PurchaseOrderItem poit = grnitem.PurchaseOrderItem;
                    Model.OrderRequestItem it = poit.OrderRequestItem;
                    Model.Item i = it.Item;
                    Model.UnitOfMeasure u = i.UnitOfMeasure;
                    Model.PurchaseOrder po = poit.PurchaseOrder;
                    Model.OrderRequest or = po.OrderRequest;
                }

                if (grn.Staff != null)
                {
                    var person = grn.Staff.Person;
                    var desg = grn.Staff.Designation;
                }
                if (grn.Staff1 != null)
                {
                    var person = grn.Staff1.Person;
                    var desg = grn.Staff1.Designation;
                }

                var model = new VerifyGRN()
                {
                    EntityGRN = grn,
                    ReceivedBy = db.VStaffDetails.FirstOrDefault(p => p.StaffID == grn.ReceivedBy),
                    //                    ItemColl = items// grnentity.GoodsReceivedNoteItems //items
                    ItemColl = grn.GoodsReceivedNoteItems.ToList()
                };

                return View(model);
            }
        }

        public ActionResult ViewGRNDetails(GRNDetailsParams parammodel)
        {
            using (var db = new SCMSEntities())
            {
                Model.GoodsReceivedNote grn = db.GoodsReceivedNotes.FirstOrDefault(p => p.Id == parammodel.GRNId);
                Model.Supplier s = grn.Supplier;
                Model.CountrySubOffice c = grn.CountrySubOffice;
                Model.Location l = c.Location;
                EntityCollection<GoodsReceivedNoteItem> grnItems = grn.GoodsReceivedNoteItems;
                foreach (GoodsReceivedNoteItem grnitem in grnItems)
                {
                    Model.PurchaseOrderItem poit = grnitem.PurchaseOrderItem;
                    Model.OrderRequestItem it = poit.OrderRequestItem;
                    Model.Item i = it.Item;
                    Model.UnitOfMeasure u = i.UnitOfMeasure;
                    Model.PurchaseOrder po = poit.PurchaseOrder;
                    Model.OrderRequest or = po.OrderRequest;
                }

                if (grn.Staff != null)
                {
                    var person = grn.Staff.Person;
                    var desg = grn.Staff.Designation;
                }
                if (grn.Staff1 != null)
                {
                    var person = grn.Staff1.Person;
                    var desg = grn.Staff1.Designation;
                }

                var model = new ViewGRN()
                {
                    EntityGRN = grn,
                    ReceivedBy = db.VStaffDetails.FirstOrDefault(p => p.StaffID == grn.ReceivedBy),
                };
                ViewBag.IsVerify = parammodel.Verify;

                //Manage approval link
                string actionType = null;
                if (model.EntityGRN.IsSubmitted && !model.EntityGRN.Verified && !model.EntityGRN.IsRejected)
                    actionType = NotificationHelper.verificationCode;
                if (actionType != null)
                    model.CanApprove = notificationService.CanApprove(currentUser, NotificationHelper.grnCode, actionType, model.EntityGRN.Id);
                else
                    model.CanApprove = false;
                model.CanEdit = (!model.EntityGRN.IsSubmitted && !model.EntityGRN.IsRejected && model.EntityGRN.Staff1.Id == currentStaff.Id) ||
                    (model.EntityGRN.IsSubmitted && model.EntityGRN.IsRejected && !model.EntityGRN.Verified && model.EntityGRN.Staff1.Id == currentStaff.Id);

                return View(model);
            }
        }

        public ActionResult LoadGRNVerifyItems()
        {
            List<ViewGRN> modelList = new List<ViewGRN>();
            foreach (Model.GoodsReceivedNote item in gRNService.GetGRNsForApproval(currentStaff))
            {
                var model = new ViewGRN()
                {
                    EntityGRN = item
                };
                modelList.Add(model);
            }
            return View(modelList);
        }

        [HttpPost]
        public ActionResult LoadGRAssetItems(VerifyGRN model)
        {
            using (var db = new SCMSEntities())
            {
                gRNService.IsGRNVerified(model.EntityGRN.Id, model.ItemColl, countryProg.Id);
            }
            GoodsReceivedNote grn = gRNService.GetGRNById(model.EntityGRN.Id);
            grn.Verified = true;
            grn.ApprovedOn = DateTime.Now;
            grn.ReceptionApprovedBy = currentStaff.Id;
            gRNService.UpdateGRN(grn);
            //send notification to preparer that GRN has been verified
            string notificationMsg = string.Format(NotificationHelper.grnApprovedMsgBody, grn.Staff1.Person.FirstName, grn.RefNumber);
            notificationService.SendNotification(grn.Staff1.Person.OfficialEmail, notificationMsg, NotificationHelper.grnsubject);
            //Notify RFP Prep Incharge
            notificationService.SendAuthorizedMsgToDocPreparers(NotificationHelper.grnCode, grn.Id);

            return ShowGRNs();

        }

        public ActionResult LoadRegsiterAsset(Guid id)
        {
            return RegisterAsset(id);
        }

        private ActionResult RegisterAsset(Guid id)
        {
            var model = new RegisterAsset()
            {
                EntityAsset = new Asset(),
                //Projects = new SelectList(ORService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber"),
                Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name"),
            };

            using (var db = new SCMSEntities())
            {
                var grnItem = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id);
                ViewBag.TotalItems = grnItem.QuantityDelivered;
                ViewBag.CurrentItem = db.Assets.Count(p => p.GoodsReceivedNoteItemId == id) + 1;
                ViewBag.GRNItemId = id;
                ViewBag.Currency = grnItem.PurchaseOrderItem.PurchaseOrder.Currency.ShortName;
                model.EntityAsset.DepreciationCurrencyId = grnItem.PurchaseOrderItem.PurchaseOrder.Currency.Id;
                ViewBag.ItemName = grnItem.PurchaseOrderItem.OrderRequestItem.Item.Name;
                Model.ProjectDonor pd = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).PurchaseOrderItem.OrderRequestItem.OrderRequest.ProjectDonor;
                ViewBag.CurrentProject = pd.ProjectNumber;
                model.EntityAsset.CurrentProjectDonorId = pd.Id;
                model.EntityAsset.OpeningAccDepreciaiton = 0;
                model.EntityAsset.AssetNumber = gRNService.GenerateAssetNo(db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id));
                model.EntityAsset.PurchaseValue = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).PurchaseOrderItem.UnitPrice;
                model.EntityAsset.PercentageDepr = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).PurchaseOrderItem.OrderRequestItem.Item.ItemClassification.PercentageDepr;
                return View("LoadRegsiterAsset", model);
            }
        }

        public ActionResult LoadOtherConsumables()
        {
            var model = new OtherConsumables()
            {
                EntityInventory = new Inventory(),
                Items = new SelectList(ORService.GetItems(countryProg.Id, "C"), "Id", "Name"),
                Inventories = invetService.GetInventoryList(countryProg.Id, null, null, "C"),
                Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name")
            };
            ViewBag.Action = "SaveOtherConsumables";
            return View("LoadOtherConsumables", model);
        }

        public ActionResult RemoveConsumableItem(Guid iventId)
        {
            using (var db = new SCMSEntities())
            {
                db.Inventories.DeleteObject(db.Inventories.FirstOrDefault(p => p.Id == iventId));
                db.SaveChanges();
                return LoadOtherConsumables();
            }
        }

        public ActionResult LoadEditConsumables(Guid iventId)
        {
            using (var db = new SCMSEntities())
            {
                Model.Inventory inv = db.Inventories.FirstOrDefault(p => p.Id == iventId);
                var model = new OtherConsumables()
                    {
                        EntityInventory = inv,
                        Items = new SelectList(ORService.GetItems(countryProg.Id, "C"), "Id", "Name"),
                        Inventories = invetService.GetInventoryList(countryProg.Id, null, null, "C"),
                        Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name")
                    };
                db.Inventories.FirstOrDefault(p => p.Id == iventId);
                model.EntityInventory.ItemId = inv.ItemId;
                ViewBag.Action = "EditInventory";
                return View("LoadOtherConsumables", model);
            }
        }

        public ActionResult EditInventory(OtherConsumables model)
        {
            using (var db = new SCMSEntities())
            {

                db.Inventories.Attach(model.EntityInventory);
                db.ObjectStateManager.ChangeObjectState(model.EntityInventory, System.Data.EntityState.Modified);
                db.SaveChanges();
                ModelState.Clear();
                return LoadOtherConsumables();
            }
        }

        public ActionResult SaveOtherConsumables(OtherConsumables model)
        {
            model.EntityInventory.CountryProgrammeId = countryProg.Id;
            if (!gRNService.IsInventoryUpdated(model.EntityInventory))
            {
                ViewBag.Response = 0;
                ViewBag.Action = "SaveOtherConsumables";
                ViewBag.msg = Resources.Global_String_AnErrorOccurred;
                model.Items = new SelectList(ORService.GetItems(countryProg.Id), "Id", "Name");
                return View("LoadOtherConsumables", model);
            }

            ViewBag.Response = 1;
            ViewBag.msg = Resources.Global_String_ProcessCompleted;
            ModelState.Clear();
            return LoadOtherConsumables();
        }

        public ActionResult LoadOtherAssets()
        {
            return LoadOtherAssetz();
        }

        [HttpPost]
        public ActionResult SaveOtherAsset(RegisterAsset AssetEntity)
        {
            AssetEntity.EntityAsset.GoodsReceivedNoteItemId = Guid.Empty;
            AssetEntity.EntityAsset.CountryProgramId = countryProg.Id;
            //check for uploaded image
            if (UserSession.CurrentSession.UploadedFile != null)
            {
                AssetEntity.EntityAsset.Image = UserSession.CurrentSession.UploadedFile;
            }
            if (!gRNService.IsAssetRegistered(AssetEntity.EntityAsset, countryProg.Id))
            {
                ViewBag.Response = 0;
                ViewBag.msg = Resources.Global_String_AnErrorOccurred;
                AssetEntity.Projects = new SelectList(ORService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber");
                AssetEntity.Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name");
                return View(AssetEntity);
            }
            //clear session image variable for further uploads
            UserSession.CurrentSession.UploadedFile = null;
            ViewBag.Response = 1;
            ViewBag.msg = Resources.Global_String_ProcessCompleted;
            ModelState.Clear();
            return LoadOtherAssetz();
            //return RedirectToAction("LoadOtherAssets");
        }

        private ActionResult LoadOtherAssetz()
        {
            var model = new RegisterAsset()
            {
                EntityAsset = new Asset(),
                Projects = new SelectList(ORService.GetProject(countryProg.Id), "Id", "Name"),
                ProjectDonors = new SelectList(ORService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber"),
                Currencies = new SelectList(ORService.GetCurrencies(countryProg.Id), "Id", "ShortName"),
                Warehouses = new SelectList(wbService.GetWarehouses(countryProg.Id), "Id", "Name"),
                Items = new SelectList(ORService.GetItems(countryProg.Id, "A"), "Id", "Name")
            };
            model.EntityAsset.DepreciationCurrencyId = countryProg.Country.CurrencyId.HasValue ? countryProg.Country.CurrencyId.Value : mbCurrency.Id;
            model.EntityAsset.UseLifeSpan = true;
            model.EntityAsset.OpeningAccDepreciaiton = 0;
            model.EntityAsset.AcquisionDate = DateTime.Today;
            return View("LoadOtherAssets", model);
        }

        public ActionResult GetAssetNo(Guid ProjectDId)
        {
            ViewBag.Html = gRNService.GenerateAssetNo(ProjectDId);
            return View("HTMLResponses");
        }

        [HttpPost]
        public ActionResult RegsiterItem(Guid id, RegisterAsset model)
        {
            using (var db = new SCMSEntities())
            {

                model.EntityAsset.GoodsReceivedNoteItemId = id;
                model.EntityAsset.CountryProgramId = countryProg.Id;
                //check for uploaded image
                if (UserSession.CurrentSession.UploadedFile != null)
                {
                    model.EntityAsset.Image = UserSession.CurrentSession.UploadedFile;
                }
                model.EntityAsset.ItemId = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).PurchaseOrderItem.OrderRequestItem.Item.Id;
                model.EntityAsset.PurchaseValue = db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).PurchaseOrderItem.UnitPrice;
                model.EntityAsset.AcquisionDate = (DateTime)db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).GoodsReceivedNote.ApprovedOn;
                model.EntityAsset.OriginalProjectId = model.EntityAsset.CurrentProjectDonorId;
                gRNService.IsAssetRegistered(model.EntityAsset, countryProg.Id);
                int totalItems, currentItemcount;
                totalItems = (Int32)db.GoodsReceivedNoteItems.FirstOrDefault(p => p.Id == id).QuantityDelivered;
                currentItemcount = db.Assets.Count(p => p.GoodsReceivedNoteItemId == id);
                //clear session image variable to allow for more uploads
                UserSession.CurrentSession.UploadedFile = null;
                if (currentItemcount == totalItems)
                {
                    return ViewUnregisteredAssets();
                }
                else
                {
                    ModelState.Clear();
                    return RegisterAsset(id);
                }
            }
        }

        public ActionResult ViewUnregisteredAssets()
        {
            Models.GRNItems modeGRN;
            List<GRNItems> GRNAssetItems = new List<GRNItems>();
            foreach (GoodsReceivedNoteItem bc in gRNService.GetUnregisteredGRNItems(countryProg.Id))
            {
                modeGRN = new GRNItems();
                modeGRN.EntityGRNItem = bc;
                GRNAssetItems.Add(modeGRN);
            }
            return View("ViewUnregisteredAssets", GRNAssetItems);
        }

        public ActionResult RegisterAsset()
        {
            return View();
        }

        public ActionResult DownloadTemplate()
        {
            return LGRN("DownloadTemplate");
        }

        public ActionResult ComputeQty(Guid packId, int? qty)
        {
            using (var db = new SCMSEntities())
            {
                if (packId == null)
                {
                    Model.ItemPackage pack = db.ItemPackages.FirstOrDefault(p => p.Id == packId);
                    ViewBag.Html = (pack.PackSize * (qty ?? 0)).ToString();
                }
                else ViewBag.Html = (qty ?? 0).ToString();//"1";
                return View("HTMLResponses");
            }
        }

        public ActionResult GetDepreciationPctge(Guid itemId)
        {
            using (var db = new SCMSEntities())
            {
                ViewBag.Html = db.Items.FirstOrDefault(p => p.Id == itemId).ItemClassification.PercentageDepr.ToString();
                return View("HTMLResponses");
            }
        }

        [HttpPost]
        public ActionResult HandleImageUpload(HttpPostedFileBase qqFile)
        {
            if (qqFile != null)
            {
                var fileContent = new byte[qqFile.ContentLength];
                qqFile.InputStream.Seek(0, SeekOrigin.Begin);
                qqFile.InputStream.Read(fileContent, 0, qqFile.ContentLength);
                UserSession.CurrentSession.UploadedFile = fileContent;
                UserSession.CurrentSession.UploadedDocDetails = new UploadedDoc() { FileContent = fileContent, FileName = qqFile.FileName, ContentLength = qqFile.ContentLength, ContentType = qqFile.ContentType };
                return Json(new { success = true }, "text/html");
            }
            else if (Request != null)
            {
                var fileContent = new byte[Request.ContentLength];
                Request.InputStream.Seek(0, SeekOrigin.Begin);
                Request.InputStream.Read(fileContent, 0, Request.ContentLength);
                UserSession.CurrentSession.UploadedFile = fileContent;
                UserSession.CurrentSession.UploadedDocDetails = new UploadedDoc() { FileContent = fileContent, ContentType = GetContentType(Request.QueryString.GetValues(0).LastOrDefault()), FileName = Request.QueryString.GetValues(0).LastOrDefault(), ContentLength = Request.ContentLength, };
                return Json(new { success = true }, "text/html");
            }
            else
            {
                UserSession.CurrentSession.UploadedFile = null;
                UserSession.CurrentSession.UploadedDocDetails = null;
                return Json(new { success = false });
            }
        }

        private string GetContentType(string fileName)
        {
            //http://codeasp.net/blogs/raghav_khunger/microsoft-net/531/how-to-get-content-type-of-a-file-in-c
            //http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files

            string contentType = "application/octetstream";
            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (registryKey != null && registryKey.GetValue("Content Type") != null)
                contentType = registryKey.GetValue("Content Type").ToString();
            return contentType;
        }

        private bool ValidateImageUploaded(RegisterAsset model, bool createMode = true)
        {
            model.AssetPictureUpload = (model.AssetPictureUpload ?? Request.Files["AssetPictureUpload"]);
            if (model.AssetPictureUpload != null && model.AssetPictureUpload.ContentLength > 0)
            {
                var fileExtension = Path.GetExtension(model.AssetPictureUpload.FileName).TrimStart(new[] { '.' });
                if (!SettingsHelper<CommonSettings>.Settings.AllowedImageExtensions.Any(p => p.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase)))
                {
                    ModelState.AddModelError("PhotoLocationUpload", Resources.GoodsReceivedNoteController_String_FileExtensionNotSupported);
                }
                else
                {
                    if (model.AssetPictureUpload.ContentLength >
                        SettingsHelper<CommonSettings>.Settings.PersonPhotoMaxSize * 1024)
                    {
                        ModelState.AddModelError("PhotoLocationUpload",
                                                 Resources.GoodsReceivedNoteController_String_ImageSizeMsg.F(
                                                     SettingsHelper<CommonSettings>.Settings.PersonPhotoMaxSize * 1024,
                                                     model.AssetPictureUpload.ContentLength));
                    }
                    else if (!m_ImageService.IsImage(model.AssetPictureUpload.InputStream))
                    {
                        ModelState.AddModelError("PhotoLocationUpload", Resources.GoodsReceivedNoteController_String_FileUploadedNotValid);
                    }
                }

                model.AssetPictureUpload.InputStream.Seek(0, SeekOrigin.Begin);
            }


            return ModelState.IsValid;
        }

        public ActionResult SearchAssetDesc()
        {
            string searchTerm = Request.QueryString["q"];
            if (UserSession.CurrentSession.AssetList == null)
                UserSession.CurrentSession.AssetList = invetService.GetAssetList(countryProg.Id);
            string searchResults = "";
            foreach (Asset asset in UserSession.CurrentSession.AssetList)
            {
                if (asset.Name.StartsWith(searchTerm, true, System.Globalization.CultureInfo.CurrentCulture))
                    searchResults += asset.Name + "\n";
            }
            searchResults = searchResults != "" ? searchResults : "\n";
            return Content(searchResults, "text/html");
        }

        public ActionResult GetWareHouses(Guid countrysubOfficeId)
        {
            StringBuilder blineOption = new StringBuilder();
            using (var db = new SCMSEntities())
            {
                blineOption.Append("<select data-val=\"true\" data-val-required=\"" + Resources.Global_String_Required + "\" id=\"EntityGRN_WareHouseId\" name=\"EntityGRN.WareHouseId\"><option value=\"\">" + Resources.Global_String_PleaseSelect + "</option>");
                foreach (WareHouse item in gRNService.GetSubOfficeWareHouses(countrysubOfficeId))
                    blineOption.Append("<option value=\"" + item.Id + "\">" + item.Name + "</option>");
                blineOption.Append("</select>");
                blineOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityGRN.WareHouseId\" data-valmsg-replace=\"false\">" + Resources.Global_String_Required + "</span>");
            }
            ViewBag.Html = blineOption.ToString();
            return View("HTMLResponses");
        }

        public ActionResult RejectGRN(Guid id)
        {
            var grn = gRNService.GetGRNById(id);
            grn.IsRejected = true;
            grn.Verified = false;
            grn.ApprovedOn = DateTime.Now;
            grn.ReceptionApprovedBy = currentStaff.Id;
            gRNService.UpdateGRN(grn);
            return Content(Resources.Global_String_Done);
        }

        public ActionResult AssetManagement()
        {
            var model = new ViewAssetInventoty()
            {
                EntityAssetInventory = invetService.GetAssetInventoryList(countryProg.Id)
            };
            return View("AssetManagement", model);
        }

        public ActionResult LoadDesposeAsset(Guid assetId)
        {
            var model = new DesposeAsset()
            {
                EntityAsset = invetService.GetAssetById(assetId)
            };
            return View(model);
        }

        public ActionResult LoadTransferAsset(Guid assetId)
        {
            var model = new TransferAsset()
            {
                EntityAssetManagement = new AssetManagment(),
                ProjectDonors = new SelectList(ORService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber")
            };
            model.EntityAssetManagement.AssetId = assetId;
            return View(model);
        }

        [HttpPost]
        public ActionResult DisposeAsset(DesposeAsset model)
        {
            gRNService.IsAssetDisposed(model.EntityAsset);
            return AssetManagement();
        }

        [HttpPost]
        public ActionResult TransferAsset(TransferAsset model)
        {
            model.EntityAssetManagement.Id = Guid.NewGuid();
            model.EntityAssetManagement.ActionTakenBy = currentStaff.Id;
            model.EntityAssetManagement.IssueDate = DateTime.Now;
            gRNService.IsAssetStateChanged(model.EntityAssetManagement);
            return AssetManagement();
        }
    }

}
